import { conf } from "../confParse.js"
import kafka from "node-rdkafka"
import cluster from "node:cluster"
import { parseConf } from "../confParse.js";
import { eventHandler, EventHandler } from "../event/eventHandler.js"
import { myLogger } from "../logger/myLogger/mylogger.js";
import {createReqStream} from "./createReqStream.js"
import {createRespProducer} from './createRespProducer.js'
import {reqHandle} from "./reqHandle.js"
class Server {
    conf:conf
    constructor() {
        this.conf=parseConf()
        this.conf.brokerList=process.env.ID?process.env.ID:"localhost:9092"
        console.log(this.conf)
        var logger = new myLogger(this.conf)
        EventHandler.setLogger(logger)

    }
    async start() {
        if (cluster.isPrimary) {
            for (let i = 1; i < this.conf.instanceNum; i++) {
                cluster.fork({ id: i })
            }
        }
        let reqStream = createReqStream(this.conf)
        let respProducer=await createRespProducer(this.conf)
        reqHandle(reqStream,respProducer,this.conf)

        //处理退出
        process.on("SIGINT", async () => {
            await eventHandler.close()
            await new Promise<void>(resolve=>{
                reqStream.consumer.disconnect(() => {
                    resolve()
                })
            })
            await new Promise<void>(resolve=>{
                respProducer.disconnect(()=>{
                    resolve()
                })
            })
            process.exit()
        })
    }
}
export { Server }